package com.example.tccdemo.consumer;

import com.example.tccdemo.db132.dao.OrderMapper;
import com.example.tccdemo.db132.model.Order;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

import static org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
import static org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus.RECONSUME_LATER;

/**
 * @describte:消费者消费方法
 * @program:distribute-transaction
 * @author:zhengdp
 * @create:2021-09-27 13:06:36
 **/
@Component("messageListener")
public class ChangeOrderStatus implements MessageListenerConcurrently {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                    ConsumeConcurrentlyContext context) {
        if(msgs == null || msgs.size() == 0){
            return CONSUME_SUCCESS;
        }
        // 默认每次只消费一条消息。可以进行设置
        for (MessageExt msg : msgs) {
            String orderId = msg.getKeys();
            String message = new String(msg.getBody());
            System.out.println("message="+message);

            Order order = orderMapper.selectByPrimaryKey(Integer.parseInt(orderId));
            if(order == null) return RECONSUME_LATER;
            try{
                order.setOrderStatus(1); // 已支付
                order.setUpdateTime(new Date());
                order.setUpdateUser(0); // 系统更新
                orderMapper.updateByPrimaryKey(order);
            }catch(Exception e){
                // 如果更新失败，就再次消费
                e.printStackTrace();
                return RECONSUME_LATER;
            }
        }
        return CONSUME_SUCCESS;
    }
}
